package com.bdqn.websocket2.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

//监听用户连接断开
public class StompDisconnectEventListener implements ApplicationListener<SessionDisconnectEvent> {


    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    SessionRegistry sessionRegistry;


    //监听用户断开连接，一旦监听到有用户断开连接，就获取最新用户名单广播给所有客户端
    //以便客户端更新用户列表
    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
        Principal principal = sha.getUser();
        List<Object> list = sessionRegistry.getAllPrincipals();//获取所有登录用户对象集合
        List<String> users=new ArrayList<>();//只需登录用户名称字符串集合
        for (Object o : list) {
            User u= (User) o;
            if(u.getUsername().equals(principal.getName())){ //排除掉刚刚下线的用户。
                continue;
            }
            users.add(u.getUsername());
        }
        //发送消息目标地址为/topic/receive，所有订阅了/topic/receiveAll的客户端将收到此消息（广播）
        // 以/topic为前缀的代表广播
        //将所有登录用户的信息广播给全体客户端
        messagingTemplate.convertAndSend("/topic/receiveAll",users);
    }
}


